using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Security.Cryptography;
using Thor.Domain;
using Thor.Models;
using Thor.WebRole.Services;

namespace Thor.WebRole.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Index()
        {
            Credentials credentials = Credentials.GetNew();

            if(Request.QueryString.Count == 1)
                credentials.ReferringUrl = Request.QueryString[0];

            return View("LogOn", credentials);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn(Credentials credentials)
        {
            credentials.Decrypt();

            if (string.IsNullOrEmpty(credentials.UserName))
                ModelState.AddModelError("UserName", "You must enter a user name!");

            if (string.IsNullOrEmpty(credentials.Password))
                ModelState.AddModelError("Password", "You must enter a password!");

            if (!ModelState.IsValid)
                return View("LogOn", credentials);

            var authSvc = new AuthenticationService();

            if (authSvc.Login(credentials.UserName, credentials.Password, credentials.Persist, null) == null)
            {
                string message = string.Empty;

                if (InvalidLogonHelper.IsLogonLocked(credentials.UserName))
                    message = "Your account has been locked.";
                else
                    message = "Invalid user name/password combination.";

                ModelState.AddModelError("UserName", message);

                return View("LogOn", credentials);
            }

            if (!string.IsNullOrEmpty(credentials.ReferringUrl))
            {
                //If we're going to the configuration app, we need to verify
                //the user is an administrator
                if (credentials.ReferringUrl.ToLower() == "/configuration")
                {
                    if (!authSvc.IsUserAdministrator(credentials.UserName))
                        return View("PermissionDenied");
                }

                return Redirect(credentials.ReferringUrl);
            }
            else
                return RedirectToAction("Index", "Calendar");
        }
    }
}